import store from "@/store"
import { defineStore } from "pinia"
import {
  IAddProjectRequestData,
  IGetProjectRequestData,
  IGetProjectResponseData,
  IUpdateRequestData
} from "@/api/project/types/project"
import { FindProjectByCondApi, AddProjectApi, DeleteProjectApi, UpdateProjectApi } from "@/api/project"
import { ref } from "vue"

export const useProjectStore = defineStore("project", () => {
  const projectList = ref<IGetProjectResponseData[]>([])
  const total = ref<number>(0)
  const getQuery = ref<IGetProjectRequestData>()
  /**
   * 增
   * @param data
   */
  const addProject = (data: IAddProjectRequestData) => {
    return new Promise((resolve, reject) => {
      AddProjectApi(data)
        .then(async () => {
          if (getQuery.value) await getProjectList(getQuery.value)
          resolve(true)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  /**
   * 删
   * @param data
   */
  const deleteProject = (data: string) => {
    return new Promise((resolve, reject) => {
      DeleteProjectApi(data)
        .then(async () => {
          resolve(true)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  /**
   * 改
   * @param data
   */
  const updateProject = (data: IUpdateRequestData) => {
    return new Promise((resolve, reject) => {
      UpdateProjectApi(data)
        .then(async () => {
          resolve(true)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  /**
   * 查
   * @param data
   */
  const getProjectList = (data: IGetProjectRequestData) => {
    getQuery.value = data
    return new Promise((resolve, reject) => {
      FindProjectByCondApi(data, 0)
        .then((res) => {
          total.value = res.data.total
          projectList.value = res.data.list
          resolve(true)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  return { getProjectList, projectList, addProject, deleteProject, updateProject }
})

/** 在 setup 外使用 */
export function useProjectStoreHook() {
  return useProjectStore(store)
}
